package com.example.demotest.controller;

import com.example.demotest.pojo.*;
import com.example.demotest.pojo.dto.ProductEditDto;
import com.example.demotest.pojo.dto.ProductRequestDto;
import com.example.demotest.repository.ProductRepository;
import com.example.demotest.service.ProductService;
import com.example.demotest.util.AliOssUtil;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
;
/*
* 负责人：孟瑞航
* 功能：接收和处理客户端发送的“发布商品”请求
* 实现：监听路径 /api/products/release 的 POST 请求，要求用户已登录（通过 JWT 传递身份信息），
*     然后将商品信息存储到数据库中，并返回操作结果
*
* */

@RestController//声明这是一个 REST 控制器，返回的是 JSON 数据而非视图
@RequestMapping("/products")//设置该控制器处理的 URL 前缀为 /products
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private JWT jwt;//于登录验证和提取用户信息

    @Autowired
    private AliOssUtil aliOssUtil;

    //上传图片接口
    //MultipartFile 用来处理前端通过 FormData 提交的文件
    @CrossOrigin("http://localhost:8081")
    @PostMapping("/upload/image")
    public ResponseMessage<String> uploadImage(@RequestParam("file") MultipartFile file) {
        //System.out.println("1111111");
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;


            // 调用阿里云 OSS 上传
            String fileUrl = aliOssUtil.upload(file.getBytes(), objectName);

            return ResponseMessage.success("上传成功", fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMessage.error("图片上传失败");
        }
    }

    /**
     * 发布商品接口
     */
    @PostMapping("/release")
    public ResponseMessage<Object> publishProduct(
            @RequestBody @Valid ProductRequestDto request,
            HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        Product product = productService.publish(request, userId);
        return ResponseMessage.success("发布成功", Map.of("productId", product.getProductID()));
    }

    //加载商品信息
    @GetMapping("/loadItem/{productId}")
    public ResponseMessage<Product> loadProduct(@PathVariable Integer productId) {
        Product product = productService.getProductById(productId);
        if(product == null) {
            return ResponseMessage.error("未找到该商品");
        }else{
            return ResponseMessage.success(product);
        }
    }

    /*
     * 编辑已发布商品接口
     *
     * */
    @PutMapping("/{productId}/edit")
    public ResponseMessage<Object> editProduct(
            @PathVariable Integer productId,
            @RequestBody @Valid ProductEditDto request,
            HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return productService.editProduct(productId, request, userId);
    }

    /*
    * 下架商品
    * */
    @CrossOrigin(origins = "http://localhost:8081", methods = {RequestMethod.PATCH, RequestMethod.OPTIONS})
    @PatchMapping("/{productId}/status")
    public ResponseMessage<Object> changeProductStatus(
            @PathVariable Integer productId,
            HttpServletRequest httpRequest
    ){
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return productService.offSaleProduct(productId, userId);
    }

    //重新上架商品
    @PatchMapping("/{productId}/republish")
    public ResponseMessage<Object> republishProduct(
            @PathVariable Integer productId,
            HttpServletRequest httpRequest
    ) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return productService.republishProduct(productId, userId);
    }

    /*获取分类列表*/
    @GetMapping("/classification")
    public ResponseMessage<Object> getAllClassification(){
        List<ProductCategory> categories = productService.getAllClassification();
        return ResponseMessage.success("分类列表获取成功", categories);
    }

    /*获取某分类下的商品*/
    @GetMapping("/{classification}/items")
    public ResponseMessage<Object> getProductsByCategory(
            @PathVariable Integer classification,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "8") int size,
            @RequestParam(required = false) String time,        // 新增：时间筛选
            @RequestParam(required = false) Boolean hot,        // 新增：是否按热度排序
            @RequestParam(required = false) String priceSort,   // 新增：价格排序
            @RequestParam(required = false) Double minPrice,    // 新增：最低价
            @RequestParam(required = false) Double maxPrice     // 新增：最高价
    ){
        Page<Product> productPage = productService.getProductsByCategory(
                classification,
                page,
                size,
                time,
                hot,
                priceSort,
                minPrice,
                maxPrice
        );
        System.out.println(productPage.getContent().get(0).getViewCount());
        return ResponseMessage.success("查询成功", productPage);
    }

    //查看当前用户发布的商品
    @GetMapping("/myProduct/published")
    public ResponseMessage<List<Product>> getMyProduct(HttpServletRequest httpRequest){
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        List<Product> products = productService.getMyProduct(userId, ProductSoldStatus.ON_SALE, ProductCheckStatus.APPROVED);//1表示上架
        return ResponseMessage.success(products);
    }

    //查看当前用户下架的商品
    @GetMapping("/myProduct/down")
    public ResponseMessage<List<Product>> getMyOffSaleProduct(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        List<Product> products = productService.getMyProduct(userId, ProductSoldStatus.OFF_SALE,ProductCheckStatus.APPROVED); // statusSold = 2 表示下架
        return ResponseMessage.success(products);
    }

    @PostMapping("/{productId}/view")
    public ResponseMessage<Object> incrementViewCount(@PathVariable Integer productId) {
        try {
            productService.incrementViewCount(productId);
            return ResponseMessage.success("浏览量增加成功");
        } catch (IllegalArgumentException e) {
            return ResponseMessage.error(404, e.getMessage());
        }
    }

    @GetMapping("/search")
    public ResponseMessage<?> fuzzySearch(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 调用服务层进行模糊搜索
            Map<String, Object> result = productService.fuzzySearch(keyword, page, size);
            return ResponseMessage.success(result);
        } catch (Exception e) {
            return ResponseMessage.error(500, "搜索失败：" + e.getMessage());
        }
    }
}